import axios from "axios";
import { getStorage } from "@/utils/auth";
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 20000,
});
// request拦截器
service.interceptors.request.use(
  (config) => {
    if (getStorage("token")) {
      config.headers["Authorization"] = getStorage("token"); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);
/**
 * 响应拦截
 */
instance.interceptors.response.use(
  (response) => {
    if (response.data) {
      const { code, data = null } = response.data;
      if (code === 200) {
        return data;
      }
      return Promise.reject(response.data);
    } else {
      // 文件上传没有返回值
      return null;
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);

export const post = (url, params = {}, opt = {}) => {
  return instance({ url, method: "POST", data: params, ...opt });
};

export const get = (url, params = {}, opt = {}) => {
  return instance({ url, method: "GET", params, ...opt });
};

export const put = (url, params = {}, opt = {}) => {
  return instance({ url, method: "PUT", data: params, ...opt });
};
